#-*- coding: UTF-8 -*-

import csv
import argparse
from aiopstools.association_analysis import alarm_association

def main(host_filepath, monitoring_data):
    # 读取host.alive文件
    with open(host_filepath, 'r') as file:
        item_data_csv_file = csv.reader(file)
        for row in item_data_csv_file:
            alarmtime = row[1:]
    alarmtime.sort()
    for i in range(len(alarmtime)):
        alarmtime[i] = int(alarmtime[i])

    results = []

    for data in monitoring_data:
        item = data['item_name']
        alarm_data_filename = data['alarm_data_file']
        alldata_filename = data['alldata_file']

        timeseries_set = []
        with open(alarm_data_filename, 'r') as file:
            item_data_csv_file = csv.reader(file)
            for row in item_data_csv_file:
                for i in range(len(row)):
                    row[i] = float(row[i])
                timeseries_set.append(row)
        
        timeseries = []
        with open(alldata_filename, 'r') as file:
            item_data_csv_file = csv.reader(file)
            for row in item_data_csv_file:
                for i in range(len(row)):
                    timeseries.append(float(row[i]))

        # 生成混合集
        mixset, alarm_number, random_number = alarm_association.mixdata(alarmtime, timeseries_set, timeseries)

        flag = alarm_association.feature_screen(mixset, alarm_number, random_number)
        results.append({'item': item,'associated': flag})

    return results

if __name__=='__main__':
    parser = argparse.ArgumentParser(description='Alarm Convergence Analysis')
    parser.add_argument('--host_file', type=str, required=True, help='Path to host.alive file')
    parser.add_argument('--monitoring_data', type=str, required=True, help='Monitoring data list')
    args = parser.parse_args()

    # 解析monitoring_data
    import ast
    monitoring_data = ast.literal_eval(args.monitoring_data)

    results = main(args.host_file, monitoring_data)
    print(results)
